package org.example.base;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;

/**
 * @author liyishan
 * @date 2024/3/8 13:31
 * @apiNote  通过BufferedReader和InputStreamReader 读取字符流，使用系统配置的默认编码
 * 使用字符数组作为缓冲区，在处理文本数据时更直观，处理大量二进制数据会有性能问题
 */
@Slf4j
public class MyRequestWrapper extends HttpServletRequestWrapper {
    private String body;

    private static final int BUFFER_SIZE = 4096 * 8;

    public MyRequestWrapper(HttpServletRequest request)throws IOException {
        super(request);
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bufferedReader = null;
        try{
            InputStream inputStream = request.getInputStream();
            if(inputStream != null){
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                char[] charBuffer = new char[BUFFER_SIZE];
                int bytesRead;
                while((bytesRead = bufferedReader.read(charBuffer)) > 0){
                    stringBuilder.append(charBuffer,0,bytesRead);
                }
            }
        }finally {
            if(bufferedReader != null){
                bufferedReader.close();
            }
        }
        body = stringBuilder.toString();
    }

    @Override
    public ServletInputStream getInputStream() {
        final ByteArrayInputStream bais = new ByteArrayInputStream(body.getBytes());

        return new ServletInputStream() {

            public boolean isFinished() {
                return false;
            }

            public boolean isReady() {
                return false;
            }

            public void setReadListener(ReadListener readListener) {

            }

            public int read() {
                return bais.read();
            }
        };
    }

    @Override
    public BufferedReader getReader() {
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }


    public String getBody() {
        return body;
    }
    public void setBody(String body) {
        this.body = body;
    }

}
